<template>
  <el-image
    @click.prevent="clickImage"
    :src="`${realSrc}`"
    fit="cover"
    :style="`width:${realWidth};height:${realHeight};`"
    :preview-src-list="realSrcList"
  >
    <div slot="error" class="image-slot">
      <i class="el-icon-picture-outline"></i>
    </div>
  </el-image>
</template>

<script>
import { isExternal } from "@/utils/validate";

export default {
  name: "ImagePreview",
  props: {
    src: {
      type: Array,
      default: () => []
    },
    width: {
      type: [Number, String],
      default: ""
    },
    height: {
      type: [Number, String],
      default: ""
    }
  },
  computed: {
    realSrc() {
      if (!this.src.length) {
        return;
      }
      let real_src = this.src[0];
      if (isExternal(real_src)) {
        return real_src;
      }
      return real_src;
    },
    realSrcList() {
      if (!this.src.length) {
        return;
      }
      let real_src_list = this.src;
      let srcList = [];
      real_src_list.forEach(item => {
        if (isExternal(item)) {
          return srcList.push(item);
        }
        return srcList.push(item);
      });
      return srcList;
    },
    realWidth() {
      return typeof this.width == "string" ? this.width : `${this.width}px`;
    },
    realHeight() {
      return typeof this.height == "string" ? this.height : `${this.height}px`;
    }
  },
  methods: {
    clickImage() {
      this.$nextTick(() => {
        let wrapper = document.getElementsByClassName(
          "el-image-viewer__actions__inner"
        );
        let downImg = document.createElement("i");
        downImg.setAttribute("class", "el-icon-download");

        wrapper[0].appendChild(downImg);
        if (wrapper.length > 0) {
          const wrapperElem = wrapper[0];
          wrapperElem.addEventListener("click", () => {
            const imgUrl = this.realSrc;
            let canvas = document.createElement('canvas')
            let ctx = canvas.getContext('2d')
            let img = new Image()
            img.crossOrigin = 'Anonymous'
            img.src = imgUrl
            img.onload = () => {
              canvas.height = 300;
              canvas.width = 300;
              ctx.drawImage(img, 0, 0, 300, 300)
              let dataURL = canvas.toDataURL('image/png')
              let link = document.createElement("a")
              link.href = dataURL
              link.download = this.getFileName(imgUrl)
              link.click()
            }
          });
        }
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.el-image {
  border-radius: 5px;
  background-color: #ebeef5;
  box-shadow: 0 0 5px 1px #ccc;
  ::v-deep .el-image__inner {
    transition: all 0.3s;
    cursor: pointer;
    &:hover {
      transform: scale(1.2);
    }
  }
  ::v-deep .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    color: #909399;
    font-size: 30px;
  }
}
</style>
